﻿using Prism.Commands;
using Prism.Mvvm;
using RSFrame.Services;
using RSModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace RSDesktop.ViewModels
{
    public class LoginWindowViewModel : BindableBase
    {
        private bool canLogin = true;
        /// <summary>
        /// 获取或设置是否可以登录
        /// </summary>
        public bool CanLogin
        {
            get { return canLogin; }
            set { SetProperty(ref canLogin, value); }
        }

        private bool ringRotation = false;
        /// <summary>
        /// 获取或设置是否显示进度条
        /// </summary>
        public bool RingRotation
        {
            get { return ringRotation; }
            set { SetProperty(ref ringRotation, value); }
        }

        private string account;
        /// <summary>
        /// 账户
        /// </summary>
        public string Account
        {
            get { return account; }
            set { SetProperty(ref account, value); }
        }

        private string password = string.Empty;
        /// <summary>
        /// 密码
        /// </summary>
        public string Password
        {
            get { return password; }
            set { SetProperty(ref password, value); }
        }

        private bool rememberPassword;
        /// <summary>
        /// 获取或设置是否记住密码
        /// </summary>
        public bool RememberPassword
        {
            get { return rememberPassword; }
            set { SetProperty(ref rememberPassword, value); }
        }

        private bool autoLogin;
        /// <summary>
        /// 获取或设置是否自动登录
        /// </summary>
        public bool AutoLogin
        {
            get { return autoLogin; }
            set { SetProperty(ref autoLogin, value); }
        }

        private bool debugMode;
        /// <summary>
        /// 获取或设置是否处于调试模式
        /// </summary>
        public bool DebugMode
        {
            get { return debugMode; }
            set { SetProperty(ref debugMode, value); }
        }

        private string errorTip;
        /// <summary>
        /// 错误提示信息
        /// </summary>
        public string ErrorTip
        {
            get { return errorTip; }
            set { SetProperty(ref errorTip, value); }
        }

        /// <summary>
        /// 用户账户服务
        /// </summary>
        public IAccountService AccountService { get; set; }

        /// <summary>
        /// 配置信息存取服务
        /// </summary>
        public IConfigurationService ConfigurationService { get; set; }

        public Workspace CurrentWorkspace { get; set; }

        public Window TopWindow { get; set; }

        public DelegateCommand LoginCommand { get; set; }

        /// <summary>
        /// 勾选自动登录命令
        /// </summary>
        public DelegateCommand CheckAutoLoginCommand { get; private set; }

        /// <summary>
        /// 勾选记住密码命令
        /// </summary>
        public DelegateCommand CheckRemeberPasswordCommand { get; private set; }

        public LoginWindowViewModel(Workspace currentWorkspace, Window window, IAccountService accountService, IConfigurationService configurationService)
        {
            AccountService = accountService;
            ConfigurationService = configurationService;
            CurrentWorkspace = currentWorkspace;
            TopWindow = window;

            LoginCommand = new DelegateCommand(ExecuteLoginAsync).ObservesCanExecute(() => CanLogin);
            CheckAutoLoginCommand = new DelegateCommand(ExecCheckAutoLogin).ObservesCanExecute(() => CanLogin);
            CheckRemeberPasswordCommand = new DelegateCommand(ExecCheckRemeberPassword).ObservesCanExecute(() => CanLogin);

            RememberPassword = ConfigurationService.RememberPassword;
            AutoLogin = ConfigurationService.AutoLogin;
            Account = ConfigurationService.Account;
            if (RememberPassword)
                Password = ConfigurationService.Password;
            if (AutoLogin)
                ExecuteLoginAsync();
        }

        private async void ExecuteLoginAsync()
        {
            CanLogin = false;
            RingRotation = true;
            ConfigurationService.RememberPassword = RememberPassword;
            ConfigurationService.AutoLogin = AutoLogin;
            try
            {
                User user = await LoginAsync();
                if (user != null)
                {
                    CurrentWorkspace.CurrentUser = user;
                    CurrentWorkspace.LoginTime = DateTime.Now;
                    TopWindow.Close();
                }
                else
                    ErrorTip = "登陆失败，请检查账户密码或网络连接";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                CanLogin = true;
                RingRotation = false;
            }
        }

        /// <summary>
        /// 使用异步方法执行登录
        /// </summary>
        /// <returns>返回登录成功的用户。若登录失败，则返回null。</returns>
        private Task<User> LoginAsync()
        {
            var result = new TaskCompletionSource<User>();
            new Thread(() => 
            {
                if (int.TryParse(Account, out int temp) && Password != string.Empty)
                    result.SetResult(AccountService.Login(temp, Password));
                else
                    result.SetResult(null);
            }) 
            { IsBackground = true }.Start();
            return result.Task;
        }

        private void ExecCheckAutoLogin()
        {
            if (AutoLogin)
                RememberPassword = true;
        }

        private void ExecCheckRemeberPassword()
        {
            if (!RememberPassword)
                AutoLogin = false;
        }

    }
}
